package com.zeng.ctrl.restmodel;

import com.alibaba.fastjson.JSONObject;
import com.zeng.bean.restmodel.RestQueryParam;
import com.zeng.bean.restmodel.RestQueryPropParam;
import com.zeng.config.restmodel.RestModelCenter;
import com.zeng.mapper.restmodel.RestModelMapper;
import com.zeng.service.restmodel.RestModelService;
import com.zeng.util.GenUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("rest/{model}")
public class RestModelController {
    @Autowired
    WebApplicationContext appContext;

    @Autowired
    RestModelCenter restModelCenter;

    @RequestMapping
    public ApiRet domian(@PathVariable String model, HttpServletRequest request) {
        String method = request.getMethod();

        RestModelService service = restModelCenter.getService(model);

        if(service == null) return ApiRet.fail("没有找到模型" + model);

        try {

            //读取url中的参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            RestQueryParam restQueryParam = RestQueryParam.defaultSelect(service.getClazz());

            List<RestQueryPropParam> whereParams = new ArrayList<>();

            parameterMap.forEach((k, v) -> {
                whereParams.add(new RestQueryPropParam(k, v[0]));
            });

            //读取请求体中的参数
            ServletInputStream inputStream = request.getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            String jsonStr = new String(bytes);
            if (!GenUtils.stringIsNullOrWhiteSpace(jsonStr)) {
                try {
                    JSONObject bodyParam = JSONObject.parseObject(jsonStr);
                    bodyParam.forEach((k, v) -> {
                        whereParams.add(new RestQueryPropParam(k, v));
                    });
                } catch (Exception ignore) {
                }
            }

            restQueryParam.setWhereParams(whereParams);

            return switch (method) {
                case "GET" -> ApiRet.success("查询成功", service.select(restQueryParam));
                case "POST" -> ApiRet.success("插入成功", service.insert(restQueryParam));
                case "PUT" -> {
                    service.update(restQueryParam);
                    yield ApiRet.success("更新成功");
                }
                case "DELETE" -> {
                    service.delete(restQueryParam);
                    yield ApiRet.success("删除成功");
                }
                default -> ApiRet.fail("不支持的方法：" + method);
            };

        } catch (SQLIntegrityConstraintViolationException sql1) {
          log.error(sql1.getMessage());
          return ApiRet.fail("您的参数违反了数据库约束", sql1.getSQLState());
        } catch (Exception e){
            log.error(e.getMessage());
            return ApiRet.fail(e.getMessage(),e);
        }
    }

}
